#include "DirectLOL/graphicElement/2DShape/texturedRect.h"
#include <stdio.h>

TexturedRect::TexturedRect(Texture * aTex) : Rect()
{
	texture=aTex;
	InitTextureBuffer();
}

TexturedRect::TexturedRect(Texture * aTex, float size) :Rect(size)
{
	texture=aTex;
	InitTextureBuffer();
}

TexturedRect::TexturedRect(Texture * aTex, float size, Vectorf translation) : Rect(size, translation)
{
	texture=aTex;
	InitTextureBuffer();
}

TexturedRect::TexturedRect(Texture * aTex, float aWidth, float aHeight) : Rect(aWidth, aHeight)
{
	texture=aTex;
	InitTextureBuffer();
}

TexturedRect::TexturedRect(Texture * aTex, float aWidth, float aHeight, Vectorf translation) : Rect(aWidth, aHeight, translation)
{
	texture=aTex;
	InitTextureBuffer();
}

void TexturedRect::InitTextureBuffer()
{
        glGenBuffers(1, &vbo->textureBuffer);
        glBindBuffer(GL_ARRAY_BUFFER, vbo->textureBuffer);

	float textures[8]=
	{
		0.0, 1.0,
		1.0, 1.0,
		1.0, 0.0,
		0.0, 0.0
	};

	glBufferData(GL_ARRAY_BUFFER,sizeof(float)*8,textures,GL_STREAM_DRAW);

}

void TexturedRect::Display()
{
	glPushMatrix();	//	On utilise PushMatrix afin que toutes les opérations sur la matrice de visualisation restent locales

        glTranslatef(translation->x(),translation->y(),translation->z());

        glRotatef(rotation->x(),1,0,0);
        glRotatef(rotation->y(),0,1,0);
        glRotatef(rotation->z(),0,0,1);

        glEnable(GL_TEXTURE_2D);

        texture->Use();

        glBindBuffer(GL_ARRAY_BUFFER, vbo->vertexBuffer);
		glVertexPointer(3, GL_FLOAT, 0, 0);

        glBindBuffer(GL_ARRAY_BUFFER,vbo->textureBuffer);
		glTexCoordPointer(2, GL_FLOAT, 0, 0);

		/* activation des tableaux de sommets */

		glEnableClientState(GL_VERTEX_ARRAY);
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo->indexBuffer);
		glDrawElements(GL_QUADS, 4, GL_UNSIGNED_INT, 0);

		/* desactivation des tableaux de sommet */

		glDisableClientState(GL_TEXTURE_COORD_ARRAY);
		glDisableClientState(GL_VERTEX_ARRAY);

		glDisable(GL_TEXTURE_2D);

		glFlush();

	glPopMatrix();
}
